package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shuqi-novel/models/cache"
	"shuqi-novel/models/mysql"
	"time"

	"shuqi-novel/novelrpc/internal/svc"
	"shuqi-novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelListLogic {
	return &NovelListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NovelListLogic) NovelList(in *novelrpc.NovelListRequest) (*novelrpc.NovelListResponse, error) {
	// todo: add your logic here and delete this line

	var novel []*novelrpc.NovelList

	key := fmt.Sprintf("list_%s", in)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		novel = mysql.NovelList(mysql.DB, novel, in)
		marshal, _ := json.Marshal(novel)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*2)
	} else {
		json.Unmarshal([]byte(result), &novel)
	}

	return &novelrpc.NovelListResponse{
		List: novel,
	}, nil
}
